package service

import (
	"hostname-and-ssh/model"
	"hostname-and-ssh/service/ssh"
	"log"
)

// PerformOperations 执行所有的操作，包括SSH秘钥、复制公钥到目标主机、设置主机名
// 同时进行操作系统识别，关闭防火墙和 SELinux 配置
func PerformOperations(config *model.Config) error {
	// 1. 生成SSH秘钥
	err := ssh.GenerateSSHKey()
	if err != nil {
		log.Printf("Failed to generate SSH key: %v", err)
		return err
	}

	// 2. 为每个主机建立 SSH 客户端
	for i := range config.Hosts {
		err := ssh.NewSSHClient(&config.Hosts[i])
		if err != nil {
			log.Printf("Failed to create SSH client for host %s: %v", config.Hosts[i].Address, err)
			return err
		}
	}

	// 3. 将公钥复制到目标主机
	err = ssh.CopySSHKeyToHost(&config.Hosts)
	if err != nil {
		log.Printf("Failed to copy SSH key to hosts: %v", err)
		return err
	}

	// 4. 设置每台主机的主机名
	for _, host := range config.Hosts {
		err = ssh.SetHostName(&host)
		if err != nil {
			log.Printf("Failed to set hostname for host %s: %v", host.Address, err)
			return err
		}
	}

	// 5. 操作系统识别并进行防火墙和 SELinux 配置
	for _, host := range config.Hosts {
		// 获取操作系统信息
		osName, _, err := ssh.GetOSInformation(&host)
		if err != nil {
			log.Printf("Failed to get OS information for host %s: %v", host.Address, err)
			return err
		}

		// 针对不同操作系统进行配置
		switch osName {
		case "centos", "rhel":
			log.Printf("Configuring CentOS/Red Hat for host %s", host.Address)
			err := ssh.ConfigureCentOS(&host)
			if err != nil {
				log.Printf("Failed to configure CentOS/Red Hat for host %s: %v", host.Address, err)
				return err
			}
		case "ubuntu":
			log.Printf("Configuring Ubuntu for host %s", host.Address)
			err := ssh.ConfigureUbuntu(&host)
			if err != nil {
				log.Printf("Failed to configure Ubuntu for host %s: %v", host.Address, err)
				return err
			}
		case "kylin":
			log.Printf("Configuring Kylin for host %s", host.Address)
			err := ssh.ConfigureKylin(&host)
			if err != nil {
				log.Printf("Failed to configure Kylin for host %s: %v", host.Address, err)
				return err
			}
		default:
			log.Printf("Unsupported OS %s for host %s", osName, host.Address)
		}
	}

	// 5. 关闭每个主机的 SSH 客户端
	for _, host := range config.Hosts {
		ssh.CloseSSHClient(&host)
	}

	return nil
}
